# -*- coding: utf-8 -*-
"""
AI写作对话框
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                             QTextEdit, QLabel, QSpinBox, QComboBox, QCheckBox,
                             QListWidget, QListWidgetItem, QProgressBar, QMessageBox,
                             QDialogButtonBox)
from PySide6.QtCore import Qt, QThread, Signal

from ..models.novel import Novel
from ..models.character import Character
from ..services.ai_writer import AIWriter


class AIWriteThread(QThread):
    """AI写作线程"""
    
    finished = Signal(str)
    error = Signal(str)
    
    def __init__(self, ai_writer: AIWriter, plot: str, characters: list, 
                 word_count: int, style: str):
        super().__init__()
        self.ai_writer = ai_writer
        self.plot = plot
        self.characters = characters
        self.word_count = word_count
        self.style = style
    
    def run(self):
        """运行AI写作"""
        try:
            result = self.ai_writer.generate_story(
                self.plot, self.characters, self.word_count, self.style
            )
            if result:
                self.finished.emit(result)
            else:
                self.error.emit("AI写作失败，请检查网络连接和API配置")
        except Exception as e:
            self.error.emit(f"AI写作出错: {str(e)}")


class AIWriterDialog(QDialog):
    """AI写作对话框"""
    
    def __init__(self, novel: Novel, ai_writer: AIWriter, parent=None):
        super().__init__(parent)
        self.novel = novel
        self.ai_writer = ai_writer
        self.generated_content = ""
        
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("AI写作助手")
        self.setMinimumSize(600, 500)
        
        layout = QVBoxLayout(self)
        
        # 剧情输入
        plot_layout = QVBoxLayout()
        plot_layout.addWidget(QLabel("剧情大纲:"))
        self.plot_edit = QTextEdit()
        self.plot_edit.setMaximumHeight(100)
        self.plot_edit.setPlaceholderText("请输入大致的剧情描述，要包含具体的场景和情节发展...")
        plot_layout.addWidget(self.plot_edit)
        layout.addLayout(plot_layout)
        
        # 参数设置
        params_layout = QVBoxLayout()
        params_layout.addWidget(QLabel("参数设置:"))
        
        # 字数设置
        word_layout = QHBoxLayout()
        word_layout.addWidget(QLabel("目标字数:"))
        self.word_count_spin = QSpinBox()
        self.word_count_spin.setRange(100, 10000)
        self.word_count_spin.setValue(1000)
        self.word_count_spin.setSuffix(" 字")
        word_layout.addWidget(self.word_count_spin)
        
        # 添加字数说明
        word_note = QLabel("(AI将尝试控制在±10%范围内)")
        word_note.setStyleSheet("color: #666; font-size: 11px;")
        word_layout.addWidget(word_note)
        
        word_layout.addStretch()
        params_layout.addLayout(word_layout)
        
        # 风格设置
        style_layout = QHBoxLayout()
        style_layout.addWidget(QLabel("写作风格:"))
        self.style_combo = QComboBox()
        self.style_combo.addItems(["小说", "散文", "诗歌", "剧本"])
        style_layout.addWidget(self.style_combo)
        style_layout.addStretch()
        params_layout.addLayout(style_layout)
        
        layout.addLayout(params_layout)
        
        # 角色选择
        char_layout = QVBoxLayout()
        char_layout.addWidget(QLabel("参与角色 (角色属性将影响AI创作):"))
        
        self.character_list = QListWidget()
        self.character_list.setMaximumHeight(150)
        self.character_list.setSelectionMode(QListWidget.MultiSelection)
        self.load_characters()
        char_layout.addWidget(self.character_list)
        
        layout.addLayout(char_layout)
        
        # 生成按钮
        generate_btn = QPushButton("开始生成章节内容")
        generate_btn.clicked.connect(self.start_generation)
        layout.addWidget(generate_btn)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        layout.addWidget(self.progress_bar)
        
        # 结果显示
        result_layout = QVBoxLayout()
        
        # 结果标题和字数显示
        result_header = QHBoxLayout()
        result_header.addWidget(QLabel("生成结果:"))
        self.word_count_label = QLabel("")
        self.word_count_label.setStyleSheet("color: #666; font-weight: bold;")
        result_header.addWidget(self.word_count_label)
        result_header.addStretch()
        result_layout.addLayout(result_header)
        
        self.result_edit = QTextEdit()
        self.result_edit.setReadOnly(True)
        result_layout.addWidget(self.result_edit)
        layout.addLayout(result_layout)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        self.use_btn = QPushButton("插入到当前章节")
        self.use_btn.clicked.connect(self.use_content)
        self.use_btn.setEnabled(False)
        button_layout.addWidget(self.use_btn)
        
        button_layout.addStretch()
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
    
    def load_characters(self):
        """加载角色列表"""
        self.character_list.clear()
        
        if not self.novel or not self.novel.characters:
            return
        
        for character in self.novel.characters:
            item = QListWidgetItem(character.name)
            item.setData(Qt.UserRole, character)
            self.character_list.addItem(item)
    
    def start_generation(self):
        """开始生成"""
        if not self.ai_writer.is_available():
            QMessageBox.warning(self, "警告", "AI服务不可用，请检查API配置")
            return
        
        plot = self.plot_edit.toPlainText().strip()
        if not plot:
            QMessageBox.warning(self, "警告", "请输入剧情大纲")
            return
        
        # 获取选中的角色
        selected_characters = []
        for i in range(self.character_list.count()):
            item = self.character_list.item(i)
            if item.isSelected():
                character = item.data(Qt.UserRole)
                selected_characters.append(character)
        
        # 开始生成
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, 0)  # 不确定进度
        
        self.write_thread = AIWriteThread(
            self.ai_writer,
            plot,
            selected_characters,
            self.word_count_spin.value(),
            self.style_combo.currentText()
        )
        
        self.write_thread.finished.connect(self.on_generation_finished)
        self.write_thread.error.connect(self.on_generation_error)
        self.write_thread.start()
    
    def on_generation_finished(self, content: str):
        """生成完成"""
        self.progress_bar.setVisible(False)
        self.result_edit.setPlainText(content)
        self.generated_content = content
        self.use_btn.setEnabled(True)
        
        # 计算中文字数（与章节字数统计保持一致）
        import re
        text = re.sub(r'\s+', '', content)
        chinese_chars = re.findall(r'[\u4e00-\u9fff]', text)
        actual_word_count = len(chinese_chars)
        target_word_count = self.word_count_spin.value()
        
        # 计算偏差百分比
        if target_word_count > 0:
            deviation = abs(actual_word_count - target_word_count) / target_word_count * 100
            deviation_text = f"偏差: {deviation:.1f}%"
            if deviation <= 10:
                color = "#008000"  # 绿色，偏差在10%内
            elif deviation <= 20:
                color = "#FF8C00"  # 橙色，偏差在20%内
            else:
                color = "#FF0000"  # 红色，偏差超过20%
        else:
            deviation_text = ""
            color = "#666"
        
        self.word_count_label.setText(f"实际字数: {actual_word_count} 字 (目标: {target_word_count} 字) {deviation_text}")
        self.word_count_label.setStyleSheet(f"color: {color}; font-weight: bold;")
    
    def on_generation_error(self, error: str):
        """生成出错"""
        self.progress_bar.setVisible(False)
        QMessageBox.critical(self, "错误", error)
    
    def use_content(self):
        """使用生成的内容"""
        self.accept()
    
    def get_generated_content(self) -> str:
        """获取生成的内容"""
        return self.generated_content 